/*
 *
 * Copyright (c) 2022 The Raptor Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "src/surface/client.h"

#include "raptor-lite/impl/config.h"
#include "raptor-lite/impl/property.h"
#ifdef _WIN32
#include "src/windows/tcp_client.h"
#else
#include "src/linux/tcp_client.h"
#endif
#include "src/common/resolve_address.h"

namespace raptor {

ClientAdaptor::ClientAdaptor(ClientHandler *handler)
    : impl_(new TcpClient(handler)) {}

ClientAdaptor::~ClientAdaptor() { delete impl_; }

raptor_error ClientAdaptor::Init() { return impl_->Init(); }

raptor_error ClientAdaptor::Start() { return impl_->Start(); }

void ClientAdaptor::Shutdown() { impl_->Shutdown(); }

raptor_error ClientAdaptor::Connect(const std::string &addr) { return impl_->Connect(addr); }

bool ClientAdaptor::SendMsg(const Slice &msg) { return impl_->SendMsg(msg); }
bool ClientAdaptor::SendMsg(const char *buff, uint32_t len) {
    if (buff == NULL || len == 0) return false;
    return impl_->SendMsg(Slice(buff, len));
}
void ClientAdaptor::Disconnect() { impl_->Disconnect(); }
bool ClientAdaptor::IsConnected() { return impl_->IsConnected(); }

raptor_error CreateClient(const Property &p, Client **out) {
    ClientHandler *handler =
        reinterpret_cast<ClientHandler *>(p.GetValue<intptr_t>(config::kClientHandler));

    *out = nullptr;

    if (!handler) {
        return RAPTOR_ERROR_FROM_STATIC_STRING("Missing kClientHandler");
    }

    std::unique_ptr<ClientAdaptor> adaptor(new ClientAdaptor(handler));

    raptor_error err = adaptor->Init();

    if (err == RAPTOR_ERROR_NONE) {
        *out = adaptor.release();
    }
    return err;
}

void DestroyClient(Client *p) {
    if (p) {
        p->Shutdown();
        delete p;
    }
}

} // namespace raptor
